<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class TaskOperate extends AdminController
{
    public $_validation = null;

    function __construct()
    {
        parent::__construct();
        $this->load->model('MTaskOperate');

        $this->_validation = Array(
            array('field' => 'task_id', 'label' => '任务', 'rules' => 'required|integer|max_length[11]')
        , array('field' => 'pay_request_id', 'label' => '所属财务申请记录', 'rules' => 'integer|max_length[11]')
        , array('field' => 'finace_id', 'label' => '财务打款人', 'rules' => 'integer|max_length[11]')
        , array('field' => 'operator_id', 'label' => '接单者', 'rules' => 'required|integer|max_length[11]')
        , array('field' => 'contact', 'label' => '买家联系方式', 'rules' => 'trim|max_length[255]')
        , array('field' => 'order_no', 'label' => '买家下单号', 'rules' => 'required|trim|max_length[64]')
        , array('field' => 'pay_method', 'label' => '为买家付款方式', 'rules' => 'trim|integer|max_length[4]')
        , array('field' => 'pay_account', 'label' => '买家接收付款的账号', 'rules' => 'trim|max_length[255]')
        , array('field' => 'coin_type', 'label' => '买家接收付款币种', 'rules' => 'trim|integer|max_length[4]')
        , array('field' => 'true_product_price', 'label' => '实际购买时商品价格', 'rules' => 'numeric')
        , array('field' => 'yunfei', 'label' => '运费', 'rules' => 'numeric')
        , array('field' => 'buyer_order_time', 'label' => '买家下单时间', 'rules' => 'max_length[32]')
        , array('field' => 'buyer_pay_time', 'label' => '买手下单付款日期', 'rules' => 'max_length[32]')
        , array('field' => 'buyer_pay_total', 'label' => '买手下单支付的钱数', 'rules' => 'numeric')
        , array('field' => 'buyer_pay_coin_type', 'label' => '买手下单付的币种', 'rules' => 'trim|integer|max_length[4]')
        , array('field' => 'true_shuadan_amount', 'label' => '应付刷单费用', 'rules' => 'numeric')
        , array('field' => 'rate_rmb', 'label' => '对人民币汇率', 'rules' => 'numeric')
        , array('field' => 'commission', 'label' => '客户要求佣金', 'rules' => 'numeric')
        , array('field' => 'intror_commission', 'label' => '中介要求中介费', 'rules' => 'numeric')
        , array('field' => 'intror_pay_account', 'label' => '中介收款账户', 'rules' => '')
        , array('field' => 'intror_contact', 'label' => '中介收联系方式', 'rules' => '')
        , array('field' => 'intror_coin_type', 'label' => '中介要求币种', 'rules' => 'numeric')
        , array('field' => 'intror_rate_rmb', 'label' => '中介费对人民币汇率', 'rules' => 'numeric')
        , array('field' => 'add_image', 'label' => '付款截图', 'rules' => '')
        , array('field' => 'add_image_1', 'label' => '付款截图1', 'rules' => '')
        , array('field' => 'add_image_2', 'label' => '附加截图2', 'rules' => '')
        , array('field' => 'add_image_3', 'label' => '附加截图3', 'rules' => '')
        , array('field' => 'add_image_4', 'label' => '附加截图4', 'rules' => '')
        , array('field' => 'add_image_5', 'label' => '附加截图5', 'rules' => '')
        , array('field' => 'comment_link', 'label' => '评论链接', 'rules' => 'trim|max_length[512]')
        , array('field' => 'status', 'label' => '状态', 'rules' => 'integer')
        , array('field' => 'payment_type', 'label' => '付款类型', 'rules' => 'required|integer')
        , array('field' => 'remark', 'label' => '备注', 'rules' => '')
        , array('field' => 'update_time', 'label' => '更新时间', 'rules' => '')
        , array('field' => 'ceping_type', 'label' => '测评类型', 'rules' => 'integer')
        , array('field' => 'true_company_cost', 'label' => '公司实际刷单成本', 'rules' => 'numeric')
        , array('field' => 'true_company_cost_rate', 'label' => '公司成本对rmb汇率', 'rules' => 'numeric')
        );
        $this->load->model('MAdmin');
        $this->load->model('MAdminGroup');
        $this->load->model('MShop');
        $allReviewsAdmin = $this->MAdmin->getAllReviewsAdmin();//所有测评人,包含销售组成员，也可以作为测试人
        $allSaleGroups = MAdminGroup::getAllGroupsByType(1);//所有销售组
        $allReviewsGroups = MAdminGroup::getAllGroupsByType(2);//所有测评组
        $allShops = $this->MShop->getAllShopsTrue();
        $allFanaceAdmin = $this->MAdmin->getAllFanceAdmin();//所有财务人员
        $this->assign('allReviewsAdmin', $allReviewsAdmin);
        $this->assign('allSaleGroups', $allSaleGroups);
        $this->assign('allReviewsGroups', $allReviewsGroups);
        $this->assign('allShops', $allShops);
        $this->assign('allFanaceAdmin', $allFanaceAdmin);
    }

    function index()
    {
        //$this->output->enable_profiler(TRUE);
        $this->load->library('FormFilter');
        $this->load->helper('formfilter');
        $this->formfilter->addFilter('op.task_id', 'where');
        $this->formfilter->addFilter('op.operator_id', 'where');
        $this->formfilter->addFilter('t.country', 'where');
        $this->formfilter->addFilter('t.group_id', 'where');
        $this->formfilter->addFilter('t.shop_id', 'where');
        $this->formfilter->addFilter('op.contact', 'where');
        $this->formfilter->addFilter('op.order_no', 'where');
        $this->formfilter->addFilter('op.status', 'where');
        $this->formfilter->addFilter('op.payment_type', 'where');
        $this->formfilter->addFilter('op.pay_method', 'where');

        if ($begintime = filterValue('task_operate_create_time_begin')) {
            $this->formfilter->addFilter('task_operate_create_time_begin', 'where', array('op.create_time >= ', strtotime($begintime . ' 00:00:00')));
        }
        if ($endtime = filterValue('task_operate_create_time_end')) {
            $this->formfilter->addFilter('task_operate_create_time_end', 'where', array('op.create_time <= ', strtotime($endtime . ' 23:59:59')));
        }

        if ($begintime = filterValue('task_operate_update_time_begin')) {
            $this->formfilter->addFilter('task_operate_update_time_begin', 'where', array('op.update_time >= ', strtotime($begintime . ' 00:00:00')));
        }
        if ($endtime = filterValue('task_operate_update_time_end')) {
            $this->formfilter->addFilter('task_operate_update_time_end', 'where', array('op.update_time <= ', strtotime($endtime . ' 23:59:59')));
        }

        $number_perpage = filterValue('taskoperate_number_perpage');
        $total_number = $this->MTaskOperate->getCount();
        $limit = $this->pagination($total_number, '', $number_perpage);
        $list = $this->MTaskOperate->getList($limit);
        $this->assign('total_number', $total_number);
        $this->assign('list', $list);
        $this->layout();
    }

    function add($task_id)
    {
        if (!is_numeric($task_id)) {
            show_error(l('id_not_null'));
        }
        //得到task_id详情
        $this->load->model('MTask');
        $task_info = $this->MTask->getById($task_id);
        $obj = $this->MTaskOperate->createVo();
        $obj->task_id = $task_id;
        $this->load->library('form_validation');
        $this->form_validation->set_rules($this->_validation);

        if ($this->form_validation->run() == TRUE) {
            $this->load->helper('populate');
            $newObj = populate((Object)((Array)$obj), $this->form_validation->post());
            $newObj->asin = $task_info->asin;
            $newObj->buyer_order_time = strtotime($newObj->buyer_order_time);
            $newObj->buyer_pay_time = strtotime($newObj->buyer_pay_time);

            //粘贴的图片
            if (!file_exists('upload/parseimg/')) {
                if (!mkdir('upload/parseimg/', DIR_WRITE_MODE, true)) {
                    echo json_encode(Array('error' => 'upload/parseimg/'));
                    return;
                }
            }
            if ($this->input->post('add_image')) {
                $add_image = $this->input->post('add_image');
                if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $add_image, $result)) {
                    $type = $result[2];
                    $new_file = "upload/parseimg/" . md5(uniqid(time()) . uniqid(time())) . ".{$type}";
                    file_put_contents($new_file, base64_decode(str_replace($result[1], '', $add_image)));
                }
                $newObj->add_image = $new_file;
            }

            if ($this->input->post('add_image_1')) {
                $add_image_1 = $this->input->post('add_image_1');
                if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $add_image_1, $result1)) {
                    $type1 = $result1[2];

                    $new_file1 = "upload/parseimg/" . md5(uniqid(time()) . uniqid(time())) . ".{$type1}";
                    file_put_contents($new_file1, base64_decode(str_replace($result1[1], '', $add_image_1)));
                }
                $newObj->add_image_1 = $new_file1;
            }

            $this->db->trans_start();
            //查询当前asin、order_no、payment_type下是否系统中已有
            $uniqueTaskOperate = $this->MTaskOperate->getAll(
                array(
                    'asin' => $newObj->asin,
                    'order_no' => $newObj->order_no,
                    'payment_type' => $newObj->payment_type,
                    'status <>' => 4
                )
            );
            if ($uniqueTaskOperate) {
                errorAndRedirect('当前asin:' . $newObj->asin . '下已有订单号为' . $newObj->order_no . '并且同一付款类型为' . $newObj->payment_type . '的记录！', site_url($this->_thisModule . $this->_thisController . '/add/' . $task_id));
            }
            if ($this->MTaskOperate->add($newObj)) {
                // 添加成功更新已录测评数量
                $this->load->model('MTaskApplyNum');
                if (!$this->MTaskApplyNum->updateCepingCount($obj->task_id, $obj->operator_id)) {
                    $this->db->_trans_status = FALSE;
                }

                //更新task表中测评/销量数
                if (!$this->MTask->updateCepingCount($obj->task_id)) {
                    $this->db->_trans_status = FALSE;
                }
                $this->db->trans_complete();
                successAndRedirect(l('edit_success'), site_url('/tasks/task/view/' . $task_id));
            } else {
                errorAndRedirect(l('data_fail'));
            }
        }
        $this->assign('obj', $obj);
        $this->layout();
    }

    function edit($id)
    {
        if (!is_numeric($id)) {
            show_error(l('id_not_null'));
        }
        $obj = $this->MTaskOperate->getOne(Array('id' => $id));
        if (!$obj) {
            errorAndRedirect('未找到定义！');
        }
        //得到task_id详情
        $this->load->model('MTask');
        $task_info = $this->MTask->getById($obj->task_id);
        $this->load->library('form_validation');
        $this->form_validation->set_rules($this->_validation);
        if ($this->form_validation->run() == TRUE) {
            $this->db->trans_start();
            $this->load->helper('populate');
            $newObj = populate((Object)((Array)$obj), $this->form_validation->post());
            $newObj->asin = $task_info->asin;
            $newObj->buyer_order_time = strtotime($newObj->buyer_order_time);
            $newObj->buyer_pay_time = strtotime($newObj->buyer_pay_time);
            if ($obj->status == 4) {
                $newObj->status = 45;
            }
            if ($obj->status == 1) {
                $newObj->status = 12;
            }
            if ($this->MTaskOperate->update($newObj)) {

                // 添加成功更新已录测评数量
                $this->load->model('MTaskApplyNum');
                if (!$this->MTaskApplyNum->updateCepingCount($obj->task_id, $obj->operator_id)) {
                    $this->db->_trans_status = FALSE;
                }

                //更新task表中测评/销量数
                if (!$this->MTask->updateCepingCount($obj->task_id)) {
                    $this->db->_trans_status = FALSE;
                }
                $this->db->trans_complete();

                successAndRedirect(l('edit_success'));
            } else {
                errorAndRedirect(l('data_fail'));
            }
        }
        $this->assign('obj', $obj);
        $this->layout();
    }

    function delete($id, $update_time)
    {
        if (!is_numeric($id) || !is_numeric($update_time)) {
            show_error(l('id_not_null'));
        }
        if (!$this->MTaskOperate->delete($id, $update_time)) {
            errorAndRedirect(l('data_fail'));
        }
        successAndRedirect(l('delete_success'));
    }

    /**
     * ajax 添加指定任务id的任务操作数据
     * @param $id
     */
    function ajaxAddTaskOperate($task_id)
    {
        if (!$this->p->add) {
            //权限不足
            model_error(l('user_has_nopower'));
        }
        if (((int)$task_id) . '' !== $task_id) {
            model_error(l('id_or_updated_not_null'));
        }
        $this->load->model('MTask');
        if (!$task = $this->MTask->getById((int)$task_id)) {
            model_error('当前任务不存在！');
        }

        $obj = $this->MTaskOperate->createVo();
        $this->load->library('form_validation');
        $this->form_validation->set_rules($this->_validation);

        if ($this->form_validation->run() == TRUE) {
            $this->load->helper('populate');
            $newObj = populate((Object)((Array)$obj), $this->form_validation->post());
            //检查是否为新客户：客户联系方式在以往测评操作记录中已经存在过算老用户，否则为新用户
            $findObj = $this->MTaskOperate->getOne(array('contact' => $newObj->contact));
            if ($findObj) {
                $newObj->is_new = 2;
            } else {
                $newObj->is_new = 1;
            }
            $newObj->order_time = strtotime($newObj->order_time);
            $newObj->pay_time = strtotime($newObj->pay_time);
            //事务添加任务操作，并修改任务表状态为已接
            $this->db->trans_start();
            if (!$this->MTaskOperate->add($newObj)) {
                $this->db->_trans_status = FALSE;
            }

            if ($task->status == MTask::STATE_NOT_ACCEPT) {
                $task->status = MTask::STATE_ACCEPTED;
                if (!$this->MTask->update($task)) {
                    $this->db->_trans_status = FALSE;
                }
            }

            $this->db->trans_complete();
            if ($this->db->trans_status() !== FALSE) {
                model_success('添加任务操作成功！');
            } else {
                model_error('添加任务操作失败！');
            }
        }

        $this->assign('obj', $obj);
        $this->assign('task', $task);
        $this->assign('thisControllerName', '添加任务操作记录');
        $this->assign('action', 'add');
        $this->layout_modal('modal-form');
    }

    /**
     * ajax 修改指定任务id的任务操作数据
     * @param unknown $id
     */
    function ajaxEditTaskOperate($task_operate_id)
    {
        if (!$this->p->add) {
            //权限不足
            model_error(l('user_has_nopower'));
        }
        if (!is_numeric($task_operate_id)) {
            show_error(l('id_not_null'));
        }
        $obj = $this->MTaskOperate->getOne(Array('id' => $task_operate_id));
        if (!$obj) {
            model_error('未找到定义！');
        }
        $this->load->model('MTask');
        if (!$task = $this->MTask->getById((int)$obj->task_id)) {
            model_error('当前任务不存在！');
        }
        $this->editObj = $obj;

        $this->load->library('form_validation');
        $this->form_validation->set_rules($this->_validation);

        if ($this->form_validation->run() == TRUE) {
            $this->load->helper('populate');
            $newObj = populate((Object)((Array)$obj), $this->form_validation->post());
            //检查是否为新客户：客户联系方式在以往测评操作记录中已经存在过算老用户，否则为新用户
            $findObj = $this->MTaskOperate->getOne(array('contact' => $newObj->contact));
            if ($findObj) {
                $newObj->is_new = 2;
            } else {
                $newObj->is_new = 1;
            }
            $newObj->order_time = strtotime($newObj->order_time);
            $newObj->pay_time = strtotime($newObj->pay_time);

            //事务添加任务操作，并修改任务表状态为已接
            if (!$this->MTaskOperate->update($newObj)) {
                $this->db->_trans_status = FALSE;
            }
            $task->status = MTask::STATE_ACCEPTED;
            if (!$this->MTask->update($task)) {
                $this->db->_trans_status = FALSE;
            }
            $this->db->trans_complete();
            if ($this->db->trans_status() !== FALSE) {
                model_success('修改任务操作成功！');
            } else {
                model_error('修改任务操作失败！');
            }
        }

        $this->assign('obj', $obj);
        $this->assign('task', $task);
        $this->assign('thisControllerName', '修改任务操作记录');
        $this->assign('action', 'edit');
        $this->layout_modal('modal-form');
    }

    /**
     * ajax 查找给定id的任务操作详情
     * @param $id
     */
    function ajaxViewDetail($id)
    {
        if (((int)$id) . '' !== $id) {
            model_error(l('id_or_updated_not_null'));
        }
        if (!$obj = $this->MTaskOperate->getById((int)$id)) {
            model_error('任务操作记录不存在！');
        }

        if (($postStatus = $this->input->post('status')) != null) {
            $this->load->model('MTask');
            $task = $this->MTask->getById($obj->task_id);
            if (!$task) {
                model_error('该任务操作对应任务不存在');
            }

            if (!($task->task_contact_id == $this->_user->id || $this->_user->role_id == 7 || $this->_user->role_id == 8)) {
                model_error('只有任务审核联系人，或者财务处理者才可以修改任务操作记录状态！');
            }

            //只有当前状态是45再次提交财务待处理时，才会添加 error_handle_time为当前处理时间
            if ($obj->status == 45) {
                $obj->error_handle_time = time();
            }

            $obj->status = $postStatus;
            $obj->remark = $this->input->post('remark');
            $obj->ceping_type = $this->input->post('ceping_type');

            if ($this->input->post('add_image_' . $id)) {

                $obj->add_image = $this->input->post('add_image_' . $id);
            }
            if ($this->input->post('add_image_1_' . $id)) {
                $obj->add_image_1 = $this->input->post('add_image_1_' . $id);
            }
            if ($this->input->post('add_image_2_' . $id)) {
                $obj->add_image_2 = $this->input->post('add_image_2_' . $id);
            }
            if ($this->input->post('add_image_3_' . $id)) {
                $obj->add_image_3 = $this->input->post('add_image_3_' . $id);
            }
            if ($this->input->post('add_image_4_' . $id)) {
                $obj->add_image_4 = $this->input->post('add_image_4_' . $id);
            }
            if ($this->input->post('add_image_5_' . $id)) {
                $obj->add_image_5 = $this->input->post('add_image_5_' . $id);
            }

            //事务处理
            $this->db->trans_start();
            if (!$this->MTaskOperate->update($obj)) {
                $this->db->_trans_status = FALSE;
            }

            //只有销售审核时才更新task_apply_num表中当前测评提交人的测评/销量数
            if ($this->_user->role_id == 2 || $this->_user->role_id == 4) {
                $this->load->model('MTaskApplyNum');
                if (!$this->MTaskApplyNum->updateCepingCount($obj->task_id, $obj->operator_id)) {
                    $this->db->_trans_status = FALSE;
                }

                //更新task表中测评/销量数
                if (!$this->MTask->updateCepingCount($obj->task_id)) {
                    $this->db->_trans_status = FALSE;
                }
            }

            //财务审核不通过，恢复可录数量
            if (($this->_user->role_id == 7 || $this->_user->role_id == 8) && $postStatus == 4) {
                $this->load->model('MTaskApplyNum');
                if (!$this->MTaskApplyNum->descApplyFinishNumber($obj->task_id, $obj->ceping_type, $obj->operator_id)) {
                    $this->db->_trans_status = FALSE;
                }

                //更新task表中测评/销量数
                if (!$this->MTask->descTaskFinishNumber($obj->ceping_type, $obj->task_id)) {
                    $this->db->_trans_status = FALSE;
                }
            }

            $this->db->trans_complete();
            if ($this->db->trans_status() !== FALSE) {
                model_success('更新任务操作状态成功！');
            } else {
                model_error('更新任务操作状态失败！');
            }
        }

        $this->assign('obj', $obj);
        $this->assign('thisControllerName', '测评记录详情');
        $this->layout_modal('modal-detail');
    }

    /**
     * ajax 请求给定order_no的所有测评记录
     */
    public function ajaxReturnRecordsByOrderNo()
    {
        $this->load->model('MTaskOperate');
        $task_id = $this->input->post('task_id');
        $order_no = $this->input->post('order_no');
        $current_id = $this->input->post('current_id');
        if ($task_id) {   //确定同一任务的情况
            if ($current_id) {
                $allTaskOperates = $this->MTaskOperate->getAll(array('task_id' => $task_id, 'order_no' => $order_no, 'id <> ' => $current_id, 'status <>' => 4)); //edit情况
            } else {
                $allTaskOperates = $this->MTaskOperate->getAll(array('task_id' => $task_id, 'order_no' => $order_no, 'status <>' => 4));   //add情况
            }
        } else {  //全局查找，非同一任务情况
            if ($current_id) {
                $allTaskOperates = $this->MTaskOperate->getAll(array('order_no' => $order_no, 'id <> ' => $current_id, 'status <>' => 4)); //edit情况
            } else {
                $allTaskOperates = $this->MTaskOperate->getAll(array('order_no' => $order_no, 'status <>' => 4));   //add情况
            }
        }

        exit(json_encode($allTaskOperates));
    }


    public function group_cepings()
    {
        $this->load->model('MTaskOperate');
        $data = $this->input->post();

        $ceping_ids = $data['ceping_ids'];
        $cepings = $this->MTaskOperate->getAllByCepingId($ceping_ids);

        //根据测评记录状态判断是否可以合并打款
        $statuses = $cepings['statuses'];
        if (count(array_unique($statuses)) != 1 || (!in_array(2, array_unique($statuses)) && !in_array(0, array_unique($statuses)))) {
            exit(json_encode([
                'status' => 0,
                'msg' => '所选测评记录中含有已被拒绝的记录或无效记录，请检查后重新提交！'
            ]));
        }
        //判断已经可以合并打款后，将ids保存到session中
        $this->session->set_userdata('PAY_REQUEST_CEPING_IDS', $ceping_ids);

        exit(json_encode([
            'status' => 1,
            'msg' => '合并成功',
        ]));
    }

    public function importExcel()
    {
        $this->load->model('MTaskRecords');
        $this->load->model('MTaskRecordItem');
        $this->load->model('MTask');
        $this->load->model('MTaskApplyNum');
        $this->load->library('PHPExcel');
        $this->load->library('PHPExcel/IOFactory');
        $file = $_FILES ['file'] ['tmp_name']; //临时文件
        $file_type = pathinfo($_FILES['file']['name'],PATHINFO_EXTENSION);
        $operator_id = $this->input->post('operator_id');
        if($file_type=='xlsx' ){
            $objReader = IOFactory::createReader('Excel2007');
        }else{
            $objReader =IOFactory::createReader('Excel5');
        }
        $objPHPExcel = $objReader->load($file);

        //默认选中sheet0表
        $sheetSelected = 0;
        $objPHPExcel->setActiveSheetIndex($sheetSelected);

        //获取表格列数
        $columnCount = $objPHPExcel->getActiveSheet()->getHighestColumn();

        //验证导入表格格式
        if ($columnCount !== 'AF'){
            exit(json_encode([
                'success' => false,
                'msg'     => '请导出正确格式的表格！（由系统提供的表格样式）.'
            ]));
        }

        $new = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
        if (count($new) == 1){
            exit(json_encode([
                'success' => false,
                'msg'     => '导入表格中暂无数据，请检查后重试！'
            ]));
        }

        $unique = array();
        unset($new[1]);
        foreach ($new as $k => $v){
            if ($v['A'] == null){
                unset($new[$k]);
            }
            if ((float)trim($v['N'])){
                $unique[] = trim($v['AF']).'N'.trim($v['N']).$v['U'];
            }
            if ((float)trim($v['P'])){
                $unique[] = trim($v['AF']).'P'.trim($v['N']).$v['U'];
            }
            if ((float)trim($v['S'])){
                $unique[] = trim($v['AF']).'S'.trim($v['N']).$v['U'];
            }
        }

        if (count(array_unique($unique)) !== count($unique)){
            exit(json_encode([
                'success' => false,
                'msg'     => '数据存在相同任务下相同订单号相同打款类型的数据，检查后重新上传！',
                '$unique' => $unique,
                'num'     => count(array_unique($unique)),
                'array_unique($unique)' => array_count_values($unique)
            ]));
        }

        $this->db->trans_start();
        foreach ($new as $k => $v){
            if ((float)trim($v['N'])){
                $v['pay_type'][] = 1;
            }
            if ((float)trim($v['P'])){
                $v['pay_type'][] = 2;
            }
            if ((float)trim($v['S'])){
                $v['pay_type'][] = 3;
            }

            //查看是否有当前任务的录入测评权限
            $auth = $this->MTaskApplyNum->getOne(['task_id' => (int)$v['AF'],'operator_id' => $operator_id]);
            if (!$auth){
                exit(json_encode([
                    'success' => false,
                    'msg'     => '第'.$k.'条数据暂无录入权限，请先去接取该任务！',
                    'data'    => $auth
                ]));
            }

            if ($auth->apply_comment_num == $auth->finish_comment_num){
                exit(json_encode([
                    'success' => false,
                    'msg'     => '第'.$k.'条数据中，该任务下可录入测评数已满，请先去接取该任务！',
                    'data'    => $auth
                ]));
            }

            //赋值
            $obj = $this->MTaskRecords->createVo();
            $obj->task_id = $v['AF'];
            $obj->asin = $v['F'];
            $obj->operator_id = $operator_id;
            $obj->true_product_price = $v['J'];
            $obj->buyer_pay_total = $v['L'];
            $obj->buyer_pay_coin_type = (int)$v['AE'];
            $obj->order_no = $v['U'];
            $obj->comment_link = $v['H'];
            $obj->buyer_order_time = strtotime($v['V']);
            $obj->buyer_pay_time = strtotime($v['R']);
            $obj->ceping_type = trim($v['O'])=='留评'?2:1;
            $obj->remark = trim($v['AA']);
            $obj->create_time = time();
            $obj->update_time = time();

            //查询相同asin/订单号/操作人的records记录
            $records = $this->MTaskRecords->getOne(['asin' => $v['F'], 'order_no' => $v['U'], 'operator_id' => $operator_id]);

            if (!$records){
                //插入records表
                $record_id = $this->MTaskRecords->add($obj);
            }else{
                $record_id = $records->id;
            }

            if (!$record_id){
                $this->db->_trans_status = FALSE;
            }else{

                if ($this->MTaskApplyNum->updateCepingRecordsCount($obj->task_id, $obj->operator_id) === FALSE) {
                    $this->db->_trans_status = FALSE;
                }
                //更新task表中测评/销量数
                if ($this->MTask->updateCepingRecordsCount($obj->task_id) === FALSE) {
                    $this->db->_trans_status = FALSE;
                }


                $itemObj = $this->MTaskRecordItem->createVo();

                $itemObj->pay_method = trim($v['AD']);
                $itemObj->record_id = $record_id;
                $itemObj->contact = trim($v['AB']);
                $itemObj->pay_account = trim($v['AC']);
                $itemObj->coin_type = (int)$v['AE'];
                $itemObj->rate_rmb = trim($v['M']);
                $itemObj->status = 0;
                $itemObj->remark = $v['AA'];
                $itemObj->create_time = time();
                $itemObj->update_time = time();

                foreach ($v['pay_type'] as $vp){
                    //验证数据库中是否含有当前相同记录
                    $old = $this->MTaskRecordItem->getAll(['record_id' => $record_id,'payment_type' => $vp]);
                    if ($old){
                        exit(json_encode([
                            'success' => false,
                            'msg'     => '第'.$k.'条数据与该任务下已有测评记录重复或冲突，检查后重新上传！',
                            '$old'    => $old
                        ]));
                    }

                    switch ($vp){
                        case 1:
                            $itemObj->amount = $v['N'];
                            break;
                        case 2:
                            $itemObj->amount = $v['P'];
                            break;
                        case 3:
                            $itemObj->amount = $v['S'];
                            break;
                    }
                    $itemObj->payment_type = $vp;
		    //先查询上次插入的id  liuwei add
		    $last_item_id = $this->db->query('select id from core_task_record_item order by id desc limit 1')->result()[0]->id;
		    $itemObj->id = $last_item_id+1;
                    if (!$this->MTaskRecordItem->add($itemObj)){
                        $this->db->_trans_status = FALSE;
                    }
                }

            }
        }
        if ($this->db->_trans_status){
            $this->db->trans_complete();
            exit(json_encode([
                'success' => true,
                'msg'     => '本次共导入测评记录'.count($new).'条，导入成功！'
            ]));
        }else{
            exit(json_encode([
                'success' => false,
                'msg'     => '未能更新测评完成数量，请稍后重试！',
                'data'    => $new
            ]));
        }

    }

    public function pythonImportExcel()
    {
        $operator_id = $this->input->post('operator_id');
        $name = md5(uniqid(time()));
        $ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
        if (!is_dir("./upload/import_excel/")) {
            mkdir("./upload/import_excel/");
        }
        if (isset($_FILES["file"])) {
            $path = "./upload/import_excel/" . $name . '.' . $ext;
            $result = move_uploaded_file($_FILES["file"]["tmp_name"], $path);
            if ($result) {
                exec('python3 import.py ' . $path . ' ' . $operator_id . ' 2>&1', $out, $res);

                if ($res == 0) {
                    $json = json_decode($out[0], true);
                    exit(json_encode($json));
                } else {
                    exit(json_encode([
                        'status' => 0,
                        'msg' => '失败',
                        'data' => $out
                    ]));
                }
            } else {
                exit(json_encode([
                    'status' => 0,
                    'msg' => '文件保存失败！'
                ]));
            }
        } else {
            exit(json_encode([
                'status' => 0,
                'msg' => '请上传文件！'
            ]));
        }
    }
}
